import json

from django import http
from django.contrib.auth import login, authenticate, logout, mixins
from django.db import DatabaseError
from django.shortcuts import render, redirect
import re
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from meiduo_mall.utils.views import LoginRequiredView
from oauth.views import logger
from users.models import User, Address  # 问题注意点
from meiduo_mall.utils.response_code import RETCODE
from django.conf import settings
from celery_tasks.email.tasks import send_verify_email
from users.utils import generate_verify_email_url, check_verify_email_token


class RegisterView(View):
    """注册"""
    # get方法访问注册页
    def get(self, request):
        """提供注册界面"""
        return render(request, 'register.html')

    # post提交表单数据
    def post(self, request):
        # 通过表单获取相应的值
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code_client = request.POST.get('sms_code')

        # 后端多种校验，主要防止其他渠道进来的垃圾数据；
        # 校验1：校验全部都必填；校验2：正则校验用户名；校验3：正则校验密码；校验4：两次输入的密码是否相同；校验5：正则校验电话号码；校验6：校验用户协议是否勾选；(该步在校验1中一起做了）
        if not all([username, password, password2, mobile, allow, sms_code_client]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')

        if not password == password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        if not re.match(r'^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 短信验证码校验:只要写入过redis的健不管过期还是删除均会返回none
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get("sms_code_%s" % mobile)
        # redis_conn.delete("sms_code_%s" % mobile)

        # 判断数据库此时的验证码是不是已过期：
        if sms_code_server is None:
            return http.HttpResponseForbidden('短信验证码过期')

        # 判断如果不为空时，那此时就需要对比验证码是否一致
        if sms_code_server.decode().lower() != sms_code_client.lower():
            return http.HttpResponseForbidden('短信验证码输入错误')

        # 创建新的用户,传入数据库中,此处使用django框架自带的用户认证，对密码自动加密；
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 登陆用户，实现状态保持；检验user是不是其成员
        login(request, user)

        response = redirect('/')
        response.set_cookie('username',user.username, max_age=settings.SESSION_COOKIE_AGE)
        # 响应用户结果
        return response


class UsernameCountView(View):
    """用户名重复检验"""
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断手机号是否重复注册12"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    """用户登陆界面"""
    def get(self,request):
        return render(request, 'login.html')

    def post(self,request):
        # 接收前端发送的三个字段值；username/password/remembered--为on时表示已选择；其中前端已校验正则；
        # account_errmsg：如果校验有问题时需要返回前端的内容；
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 验证用户信息，使用authenticate验证，如果不通过，则会返回none;
        user = authenticate(request, username=username, password=password)
        if user is None:
            return render(request, 'login.html', {"account_errmsg": '用户名或密码错误'})
        # 校验是否勾选需要记住登陆，如果不勾选，默认会话结束即过期，如果勾选，则默认存储2周；注意：该处的过期只是浏览器已经过期，数据库中还存在该键；
        if remembered != 'on':
            request.session.set_expiry(0)
        # 此处为了响应设置cookie为了给前端提取用户名，并作展示；
        # 为后期用户中心返回之前登陆页面作准备：
        response = redirect(request.GET.get('next') or '/')
        response.set_cookie('username', user.username, max_age= (settings.SESSION_COOKIE_AGE) if remembered else None)
        # 状态保持：
        login(request, user)
        # 合并购物车的数据
        merge_cart_cookie_to_redis(request,response)

        return response


class LogoutView(View):
    """退出登陆"""
    def get(self, request):
        # 清除当前登陆对象
        logout(request)
        # 创建响应对象
        response = redirect('/login/')
        # 删除cookie中的username
        response.delete_cookie('username')
        return response


# class InfoView(View):
#     def get(self,request):
#         if request.user.is_authenticated:   #如果返回是true,则说明有登陆对象；
#             return render(request, 'user_center_info.html')
#         else:
#             return redirect('/login/?next=/info/')

class InfoView(mixins.LoginRequiredMixin, View):
    """用户中心"""
    # LoginRequiredMixin
    def get(self, request):
        return render(request, 'user_center_info.html')


class EmailView(LoginRequiredView):
    """定义邮箱存储"""
    def put(self,request):
      # 非表单的方法获取邮箱值
      json_dict = json.loads(request.body.decode())
      email = json_dict.get('email')
      # 对获取到的数据进行校验
      if email is None:
          return http.HttpResponseForbidden('缺少必传参数')
      if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
          return http.HttpResponseForbidden('邮箱格式错误')
      # 如果没有问题则更新到数据库；(获取到当前用户）
      user = request.user
      User.objects.filter(id=user.id, email='').update(email=email)
      # 点击保存时同时发送邮件；
      verify_url = generate_verify_email_url(user)
      send_verify_email.delay(email, verify_url)

      # 响应
      return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class VerifyEmailView(View):
    """激活用户邮箱"""
    def get(self,request):
        # 获取链接的token;
        token = request.GET.get('token')
        # 校验token是否有值；
        if token is None:
            return http.HttpResponseForbidden('缺少参数')
        # 在对token进行解密，解密或获取里面的User - id和email要查询出激活邮箱的那个user;
        user = check_verify_email_token(token)
        if user is None:
            return http.HttpResponseForbidden('无效token')
        # 修改user的email_active字段，设置为True
        user.email_active = True
        user.save()
        # 重定向到info界面；
        return redirect('/info/')


class AddressView(LoginRequiredView):
    """收货地址页面"""
    def get(self, request):
        # 获取当前用户
        user =request.user
        # 找到当前用户中所有的地址，拼接成[{}]的形式返回前端
        address_qs = Address.objects.filter(user=user,is_deleted=False)
        address_list = []    #使用列表形式存储数据；
        for address in address_qs:
            address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            }
            address_list.append(address_dict)
            # 将数据拼接成字典形式传输；
        context = {
                'addresses': address_list,
                'default_address_id': user.default_address_id,
            }
        return render(request, 'user_center_site.html', context)


class CreateAddressView(LoginRequiredView):
    """新增地址"""
    def post(self, request):
        # 获取当前用户，并判断当前有多少个地址
        user = request.user
        count = Address.objects.filter(user=user, is_deleted=False).count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.MAXNUM, 'errmsg': '收货地址超限'})

        # 接收前端传输的数据(非表单）
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验格式；1）校验参数是否齐，校验手机号码/邮箱/电话；
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        # 没问题就存入数据库；如果当前用户没有默认地址，则把该条地址设为默认地址；
        try:
            address = Address.objects.create(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('添加收货地址失败')

        if user.default_address is None:
            user.default_address = address
            user.save()

        # 拼接成json数据返回给到前端；可以传多几个字段
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加收货成功', 'address': address_dict})


class UpdateDestroyAddressView(LoginRequiredView):
    """修改收货地址"""
    def put(self, request, address_id):
        """"""
        # 查找该用户下的该id值；
        try:
            address = Address.objects.get(id=address_id,user= request.user,is_deleted=False)
        except:
            http.HttpResponseForbidden('修改收货地址失败')
        # 接收请求体中地址数据
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验请求体中的字段值；
        if all([title, receiver, province_id, city_id, district_id, place, mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        try:
            address.title = title
            address.receiver = receiver
            address.province_id = province_id
            address.city_id = city_id
            address.district_id = district_id
            address.place = place
            address.mobile = mobile
            address.tel = tel
            address.email = email
            address.save()
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('修改收货地址失败')

        #将获取到的数据转为字典传给前端；
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改收货地址成功', 'address': address_dict})

    def delete(self,request, address_id):
        """删除地址"""
        # 查找对象
        try:
            address = Address.objects.get(id=address_id,user=request.user,is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('删除收货地址失败')

        # 将is_deleted置为true
        address.is_deleted = True
        address.save()
        # 响应给前端
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class DefaultAddressView(LoginRequiredView):
    """设置用户默认地址"""
    def put(self,request,address_id):
        # 获取到对象
        try:
            address = Address.objects.get(id=address_id,user=request.user,is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('设置默认收货地址失败')
        # 将后台默认的地址更改过来；
        request.user.default_address = address
        request.user.save()
        #响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg':'OK'})

class UpdateTitleAddressView(LoginRequiredView):
    """更改用户地址的标题"""
    def put(self,request,address_id):
        # 获取前端的用户id
        try:
            address = Address.objects.get(id=address_id, user=request.user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('设置收货地址标题失败')
        # 获取前端传过来的新title
        title_dict = json.loads(request.body.decode())
        title = title_dict.get('title')

        if title is None:
            return http.HttpResponseForbidden('缺少必传参数')

        # 修改数据库的标题
        address.title = title
        address.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class ChangePasswordView(LoginRequiredView):
    """用户密码修改"""
    def get(self, request):
        return render(request, 'user_center_pass.html')

    def post(self,request):
        # 获取前端传过来的表单数据
        old_pwd = request.POST.get('old_pwd')
        new_pwd = request.POST.get('new_pwd')
        new_cpwd = request.POST.get('new_cpwd')

        # 查找该用户
        user = request.user
        print(user)
        print(user.email)

        # 校验
        if all([old_pwd,new_pwd,new_cpwd]) is False:
            return http.HttpResponseForbidden('参数不齐全')
        if user.check_password(old_pwd) is False:
            return render(request,'user_center_pass.html', {'origin_pwd_errmsg':'原始密码不正确'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_pwd):
            return http.HttpResponseForbidden('请输入8-20位长度的密码')
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden('两次密码输入的不一致')
        #将新的密码写入数据库，同时返回到登陆页面，并且需要清楚cookie
        user.set_password(new_pwd)
        user.save()
        # 重定向到logout
        return redirect('/logout/')


class HistoryGoodsView(View):
    """商品浏览记录"""
    # 该方法由detail.js页面发起的post请求
    def post(self,request):
        # 判断用户是否登录
        if not request.user.is_authenticated:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
        # 获取请求体中的sku_id
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")

        try:
            sku =SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id无效')
        # 创建redis连接对象:存储sku_id到re gadis,先去重,再添加记录到最头部,最多存5条记录截取;

        redis_conn = get_redis_connection('history')
        p1 = redis_conn.pipeline()
        # 存储每个用户redis的唯一key
        key = 'history_%s' % request.user.id

        p1.lrem(key, 0, sku_id)

        p1.lpush(key, sku_id)

        p1.ltrim(key, 0, 4)
        # 响应
        p1.execute()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

    def get(self,request):
        """获取用户商品浏览记录"""
        # 判断用户是否登录
        if not request.user.is_authenticated:
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        # 存储每个用户的redis唯一key, 获取当前用户的浏览记录数据
        key = 'history_%s' % request.user.id
        sku_id_list = redis_conn.lrange(key,0,-1)
        # 定义一个列表，用来装字典数据；
        sku_list = []
        # 遍历列表，有顺序去获取sku模型；
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id =sku_id)
            sku_list.append(
                {'id': sku.id,
                 'name': sku.name,
                 'default_image_url': sku.default_image.url,
                 'price': sku.price
                }
            )
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','skus':sku_list})






















































